﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management;
using System.Threading.Tasks;

namespace Del1C
{
    class Uninstaller1C : ObservableCollection<InstalledVersion1C>
    {
        public static Task<List<InstalledVersion1C>> GetListVersions()
        {
            return Task.Run(() =>
            {
                List<InstalledVersion1C> list = new List<InstalledVersion1C>();

                string scope = "root\\CIMV2";
                string query = "SELECT * FROM Win32_Product WHERE Vendor = '1C' OR Vendor = '1С'"; //"SELECT * FROM Win32_Product WHERE Name LIKE '%:Предприятие 8%'";

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

                var objList = searcher.Get();

                foreach (ManagementObject soft in objList)
                {
                    string name = soft.Path.Path.Split(',')[1];
                    string version = soft.Path.Path.Split(',')[2];

                    name = name.Substring(0, name.Length - 1).Replace("Name=\"", "");
                    version = version.Substring(0, version.Length - 1).Replace("Version=\"", "");


                    InstalledVersion1C instVerItem = new InstalledVersion1C(name, version, false, States.Installed, soft);
                    list.Add(instVerItem);
                }


                return list;
            });
        }

        public async Task GetVersions()
        {

            this.ClearItems();

            var list = await GetListVersions();
            var sortedList = list.OrderBy(x => x.Version);
            foreach (var item in sortedList)
            {
                this.Add(item);
            }
            foreach (var item in this)
            {
                item.Index = this.IndexOf(item);
            }
        }
    }
}
